var service = new EbeimService();
var service2 = new EbeimService2();
var onceKey = true;
var pathNodes = [];
var titleCount = 0;
var pathSet = {
		async: {
            enable: true,
            url: "/rest/system/dirs",
            autoParam: ["path"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	var nodes = [];
                getPathTree(responseData,nodes);
                return nodes;
            	
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: pathClick
        }
    };

$(function(){
	
	$("#w-page").keyup(function(){
		if(event.keyCode == 13){
			var flag = $("#w-page").val();
			page(flag);
		}
	});
	
	/*$(".folder-scroll").scroll(function(){
		if($allPage < $startPorts){
			return false;
		}
		var t = $(this);
		if((t.scrollTop() + t.height()) >= $("#j-table").height()){
			service.getFileList({
				startPorts:++$startPorts,
				pageSize:$pageSize,
				dsId:$dsId,
				version:$version,
				path:encodeURIComponent($path)
			}, getVersionTreeCB);
		};
	});*/
	var $topHistory = 0;
	$(".folder-scroll").scroll(function(){
		var t = $(this);
		if(t.scrollTop() > $topHistory){
			$topHistory = t.scrollTop();
			if((t.scrollTop() + t.height()) >= $("#j-table").height()){
				if($allPage > $endPorts){
					$startPorts++;
					$endPorts++;
					$addType = "append";
					service.getFileList({
						startPorts:$startPorts,
						endPorts:$endPorts,
						pageSize:$pageSize,
						dsId:$dsId,
						version:$version,
						path:encodeURIComponent($path)
					}, getVersionTreeCB);
				}
				/*if(!$onceDown && $allPage >= ($startPorts+4)){
					$onceDown = true;
					$onceUp = false;
					$startPorts += 4;
					$addType = "append";
					service.getFileList({
						startPorts:$startPorts,
						pageSize:$pageSize,
						dsId:$dsId,
						version:$version,
						path:encodeURIComponent($path)
					}, getVersionTreeCB);
				}*/
			};
		}else{
			$topHistory = t.scrollTop();
			if(t.scrollTop() <= 0){
				if($startPorts > 1){
					$startPorts--;
					$endPorts--;
					$addType = "prepend";
					service.getFileList({
						startPorts:$startPorts,
						endPorts:$endPorts,
						pageSize:$pageSize,
						dsId:$dsId,
						version:$version,
						path:encodeURIComponent($path)
					}, getVersionTreeCB);
				}
				/*if(!$onceUp && ($startPorts - 4) >= 1){
					$onceDown = false;
					$onceUp = true;
					$startPorts -= 4;
					$addType = "prepend";
					service.getFileList({
						startPorts:$startPorts,
						pageSize:$pageSize,
						dsId:$dsId,
						version:$version,
						path:encodeURIComponent($path)
					}, getVersionTreeCB);
				}*/
			};
		}
	});
	
	var jopenFolder = $("#j-openFolder"),
		jopenFile = $("#j-openFile");
	
	jopenFolder.click(function(){
		service.openFolder({},function(json){
			if(json.code == "200"){
				if(!json.path){
					return false
				}
				importDs(json.path);
			}else{
				if(json.code == "900"){
					return false;
				}
				plugin.msgtip({type: "e", msg: json.msg});
			}
		})
	})
	
	jopenFile.click(function(){
		service.openFile({},function(json){
			if(json.code == "200"){
				if(!json.path){
					return false
				}
				importDs(json.path);
			}else{
				if(json.code == "900"){
					return false;
				}
				plugin.msgtip({type: "e", msg: json.msg});
			}
		})
	})
	
	$(".filechangelog-ul").delegate(".j-recoveryBtn","click",function(){
		var version = $(this).attr("data-version");
		var dsId = $(this).attr("data-dsId");
		var isRoot = $(this).attr("data-isRoot");
		
		$("#h_whichGetModel").val("recovery");
		$("#h_version").val(version);
		$("#h_dsId").val(dsId);
		if(isRoot=="true"){
			$("#h_path").val("/");
		}
		
		service.openFolder({},function(json){
			if(json.code == "200"){
				if(!json.path){
					return false
				}
				$("#h_abDir").val(json.path);
				recovery(version);
			}else{
				plugin.msgtip({type: "e", msg: json.msg});
			}
		})
	})
	
	$W = $(window).width();
	$H = $(window).height();
	w = $(".window").width(); 
	h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
//	setInterval("getDownloadProcessBar()", 2500);
	setInterval("getUploadProcessBarAll()", 2500);
	setInterval("getDownloadProcessBarAll()", 2500);
	setInterval("getImportDsBeanList()", 2500);
	
	
	$("#ab-dir").keydown(function(){
		if (event.keyCode == 13) { 
			var val = $(this).val();
			val = val.replace(/\//g, "\\");
			if(val.charAt(val.length - 1) == ":"){
				val = val+"\\";
			}
			$(this).val(val);
			selectRecoveryPath(val);
		}
	})
	
	$(".w-dir-list").delegate(".j-path","click",function(){
		var val = $(this).attr("data-path");
		selectRecoveryPath(val);
	})
	
	$(".w-dir-list").delegate(".j-recovery","click",function(){
		var val = $(this).attr("data-path");
		selectRecoveryPath(val,"recovery");
	})
	
});

function importFunc(){
	$("#h_whichGetModel").val("importDs");
	selectSafeboxPath("");
}

function importDs(path){
	var abDir = $("#ab-dir").val();
	if (path /*abDir*/ == "") {
		plugin.msgtip({type: "e", msg: "请选择路径！"});
		return;
	}
	var s_path = path /*abDir*/;
	
	var name = s_path;
	var idx = s_path.lastIndexOf("\\");
	if(idx == s_path.length-1){
		s_path = s_path.substring(0,idx);
	}
	idx = s_path.lastIndexOf("\\");
	if(idx != -1){
		name = s_path.substring(idx+1,s_path.length);
	}
	var ds = {
		name : name,
		dsType : 2,
		isOpenLocalBackup : 0,
		dsSecurityRank : 0,
	};
	var bs = {
		type : 2,
		backupTime : 0,
		backupCycle : 1,
		backupPeriod : 1,
	}
	var config = {
		isEncrypt:1,
		root : path /*abDir*/,
	}
	var p = $("#currentPath").html();
	p = p.split("\\\\").join("\\");
	var bean = {
		startPorts:1,
		pageSize:$pageSize,
		dsId:$dsId,
		version:$version,
		path:p
	}
	var json = {};
	json["datasource"] = ds;
	json["datasourceConfig"] = config;
	json["backStrategy"] = bs;
	json["bean"] = bean;
	$("#confirmBtn").css("color","gray");
	service.importDs(json, function(data){
		if(data.code=="200"){
			clearDateAndWindow();
			plugin.msgtip({type: "o", msg: "成功加入队列"});
//			var v = data.version + ".0";
//			$version = v;
//			initTree(true);
//			getVersionTree($dsId, $path, $version, $root, 1);
		}else{
			plugin.msgtip({type: "e", msg: data.message});
			$("#confirmBtn").css("color","#fff");
			return;
		}
	});
//	service.addDataSource(json, importDsCB);
};
var importDsCB = function(data){
	clearDateAndWindow();
	var json = data;
	if (json.code == 200 || json.code == "200") {
		plugin.msgtip({type: "o", msg: "导入成功!即将进行上传!"});
		handBackup(json.dsId, 0);
		setTimeout(function(){
			getDateSoucesByPage();
		}, 1000);
	} else {
		dsSecurityRankCheck(json,json.message);
	}
}

function deleteUploadBar(dsId){
	if(!dsId){
		dsId = "";
		$(".delUploadBtn").each(function(){
			dsId += $(this).attr("id")+",";
		});
		if(dsId.length>0){
			dsId = dsId.substring(0,dsId.length-1);
		}
	}
	if(!dsId || dsId.length==0){
//		plugin.msgtip({type:"e",msg:"还没有可以删除的记录!"});
		return;
	}
	service.deleteUploadProcessBar(
		{
			dsIds:dsId
		},
		function(data){
			$(".j-deleteUp").css("display","none");
			$(".j-undeleteUp").css("display","inline-block");
		}
	);
}

function deleteDownloadBar(nid){
	if(!nid){
		nid = "";
		$(".delDownloadBtn").each(function(){
			nid += $(this).attr("id")+",";
		});
		if(nid.length>0){
			nid = nid.substring(0,nid.length-1);
		}
	}
	if(!nid || nid.length==0){
		plugin.msgtip({type:"e",msg:"还没有可以删除的记录!"});
		return;
	}
	service.deleteDownloadProcessBar({
		nids:nid
	}, function(data){
		//TODO
		$(".j-deleteDown").css("display","none");
		$(".j-undeleteDown").css("display","inline-block");
	});
}

$uploadTag = 0;
function getUploadProcessBarAll(){
	service.getUploadProcessBarAll({
		dsType:2
	}, function(data){
		var beans = data.beans;
		var uploadProcessbarContent = "";
		var tag = $uploadTag + beans.length;
		var jtag = $("#upload_process_tag").siblings(".j-tag");
		if(tag > 0){
			$("#upload_process_tag").css("display","block");
			$("#upload_process_tag").html(tag);
			jtag.css("display","block");
			jtag.html(tag);
			jtag.stop();
			jtag.animate({padding:"8px",top:"-10px",right:"-5px",opacity:"0"},500,function(){
				$(this).css({padding:"3px",top:"-5px",right:"0",display:"none",opacity:"1"});
			})
		}else{
			$("#upload_process_tag").css("display","none");
		}
		for(var i = 0; i<beans.length; i++){
			var bean = beans[i];
			var fs = bean.fileSum - (bean.okSum + bean.errorSum);
			var p = Math.floor((bean.count * 100 / bean.total)*100)/100;
			if(bean.total==0){
				p = 100;
			}
			var info = "";
			var btn = "";
			if(p == 0 && fs>0){
				info="上传队列中..."
			}else if(bean.errorSum>=bean.fileSum && bean.errorSum != 0){
				info="<span style='color:red'>上传失败!</span>"
				$(".j-deleteUp").css("display","inline-block");
				$(".j-undeleteUp").css("display","none");
			}else if(p >= 100 || fs<=0){
				info = "文件校验中<img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>";
				p = 100;
				btn = "<a class='delUploadBtn' id='"+bean.dsId+"' href='javascript:deleteUploadBar(\""+bean.dsId+"\");'>删除</a>";
//				$(".j-deleteUp").css("display","inline-block");
//				$(".j-undeleteUp").css("display","none");
				if(titleCount!=beans.length){
					changeTitleCount();
				}
			}else{
				info = "上传进度:"+ p + "%";
			}
			uploadProcessbarContent = uploadProcessbarContent
			+"<tr>"
			+"	<td><nobr title='"+bean.name+"' style='max-width:200px;display:inline-block;overflow:hidden;text-overflow:ellipsis;'>"+bean.name+"</nobr></td>"
			+"	<td width='150px' style='font-size:12px;text-align:center;'>"+getTimeStr(bean.createtime)+"</td>"
			+"	<td width='150px' style='text-align:center;' dsid='"+bean.id+"' class='processTD'>"
			
			+"<div class='processbar' style='background:#999;width:100px;height:20px;position:relative;margin:0 auto;'>"
			+ "<div class='bar' style='height:20px;background:green;width:"+p+"%;'></div>"
			+ "<div class='info' style='font-size:12px;width:100px;height:20px;color:#fff;position:absolute;top:0;left:0'>"
			+	info
			+" </div>"
			+"</div>"
			
			+"</td>"
			+"	<td width='60px;' style='text-align:center;'>"+btn+"</td>"
			+"</tr>";
		}
		$("#uploadProcessbarTB").html(uploadProcessbarContent);
		titleCount=beans.length;
	});
}

function changeTitleCount(){
	var title=$("title").text();
	var titleStr = "0";
	$("title").text(title+"|"+titleStr);
	$("title").text(title);
}

function getDownloadProcessBarAll(){
	service.getDownloadProcessBarAll({
		dsType:2
	}, function(data){
		var beans = data.beans;
		var downloadProcessbarContent = "";
		var jtag = $("#download_process_tag").siblings(".j-tag");
		if(beans.length > 0){
			$("#download_process_tag").css("display","block");
			$("#download_process_tag").html(beans.length);
			jtag.css("display","block");
			jtag.html(beans.length);
			jtag.stop();
			jtag.animate({padding:"8px",top:"-10px",right:"-5px",opacity:"0"},500,function(){
				$(this).css({padding:"3px",top:"-5px",right:"0",display:"none",opacity:"1"});
			})
		}else{
			$("#download_process_tag").css("display","none");
		}
		for(var i = beans.length-1; i>=0; i--){
			var bean = beans[i];
			var fs = bean.fileSum - (bean.okSum + bean.errorSum);
			var p = (Math.floor((bean.count * 100 / bean.total)*100)/100).toFixed(2);
			var info = "";
			var btn = "";
			var barColor = "green";
			if(p == 0 && fs>0){
				info="连接中..."
			}else if(bean.errorSum>=bean.fileSum && bean.errorSum != 0){
				info="<span style='color:red'>下载失败!</span>"
				barColor = "#999";
				btn = "<a class='delDownloadBtn' id='"+bean.nid+"' href='javascript:deleteDownloadBar(\""+bean.nid+"\");'>删除</a>";
				$(".j-deleteDown").css("display","inline-block");
				$(".j-undeleteDown").css("display","none");
			}else if(p >= 100 || fs<=0){
				info = "下载完成!";
				p = 100;
				btn = "<a class='delDownloadBtn' id='"+bean.nid+"' href='javascript:deleteDownloadBar(\""+bean.nid+"\");'>删除</a>";
				$(".j-deleteDown").css("display","inline-block");
				$(".j-undeleteDown").css("display","none");
			}else{
				info = "下载进度:"+ p + "%";
			}
			var path=bean.name;
			if (path.substr(0,1)=='\\') 
			{path=path.substr(1)};
			downloadProcessbarContent = downloadProcessbarContent
			+"<tr>"
			+"	<td><nobr title='"+path+"' style='max-width:200px;display:inline-block;overflow:hidden;text-overflow:ellipsis;'>"+path+"</nobr></td>"
			+"	<td width='150px' style='font-size:12px;text-align:center;'>"+getTimeStr(bean.createtime)+"</td>"
			+"	<td width='150px' style='text-align:center;' dsid='"+bean.id+"' class='processTD'>"
			
			+"<div class='processbar' style='background:#999;width:100px;height:20px;position:relative;margin:0 auto;'>"
			+ "<div class='bar' style='height:20px;background:"+barColor+";width:"+p+"%;'></div>"
			+ "<div class='info' style='font-size:12px;width:100px;height:20px;color:#fff;position:absolute;top:0;left:0'>"
			+	info
			+" </div>"
			+"</div>"
			
			+"</td>"
			+"	<td width='60px;' style='text-align:center;'>"+btn+"</td>"
			+"</tr>";
		}
		$("#downloadProcessbarTB").html(downloadProcessbarContent);
	});
}

function showUploadBar(){
	showDialog('uploadWindow');
}
function showDownloadBar(){
	showDialog('downloadWindow');
}
function showImporting(){
	showDialog('importingWindow');
}
var getVersionTreeCB = function (data) {
    var json = data.list;
    var str = '';
    $allPage = data.allPage;
    for (i = 0; i < json.length; i++) {
        var f = json[i];
        var path = f.path.split("\\\\").join('\\');
        path = path.split("\\").join('\\\\');
        var fileSize = "-";
        var icon = "";
        var f_name = "";
        var status = f.status;
        if(status == "删除"){
        	
            if(f.type == "文件"){
            	fileSize = fileSizeTransfer(f.fileSize);
            	icon = "<a href='javascript:;'><i class='inline-block folder-icon folder-dele-file'></i></a>";
            	f_name = "<span title='"+f.name+"'>"+f.name+"</span>"
            }else{
            	icon = "<a href='javascript:$startPorts = 1;$endPorts = 4;$addType = null;getVersionTree(\""+$dsId+"\",\""+path+"\",\""+$version+"\");'><i class='inline-block folder-icon folder-dele-folder'></i></a>";
            	f_name = "<span title='"+f.name+"' style='cursor:pointer;' onClick='javascript:$startPorts = 1;$endPorts = 4;$addType = null;getVersionTree(\""+$dsId+"\",\""+path+"\",\""+$version+"\");'>"+f.name+"</span>"
            }
        	status = "<font color='red'>删除</font>";
        	str+="<tr class='del-class'>";
        	
        }else{
        	
        	if(f.type == "文件"){
            	fileSize = fileSizeTransfer(f.fileSize);
            	var idx = f.name.lastIndexOf(".");
				var suffix = f.name.substring(idx+1,f.name.length);
				var icoType ;
				switch(suffix.toLowerCase()){
					case "doc" : case "docx" : 
						icoType = "folder-doc";
						break;
					case "xls" : case "xlsx" : 
						icoType = "folder-xls";
						break;
					case "ppt" : case "pptx" : 
						icoType = "folder-ppt";
						break;
					case "bmp" : case "gif" : case "jpg" : case "jpeg" : case "png" : case "psd" : case "svg" : case "ico" : case "tga" : case "ai" : 
						icoType = "folder-img";
						break;
					case "avi" : case "rmvb" : case "rm" : case "asf" : case "divx" : case "mpg" : case "mpeg" : case "mpe" : case "wmv" : case "mp4" : case "mkv" : case "vob" : case "flv" : 
						icoType = "folder-mov";
						break;
					case "html" : case "xhtml" : case "xml": 
						icoType = "folder-html";
						break;
					case "apk": 
						icoType = "folder-apk";
						break;
					case "rar" : case "zip" : case "cab" : case "arj" : case "lzh" : case "ace" : case "7z" : case "tar" : case "gzip" : case "uue" : case "bz2" : case "jar" : case "iso" : case "z" : 
						icoType = "folder-rar";
						break;
					case "mp3" : case "wma" : case "rm" : case "wav" : case "midi" : 
						icoType = "folder-mp3";
						break;
					case "txt" : 
						icoType = "folder-txt";
						break;
					case "pdf" : 
						icoType = "folder-pdf";
						break;
					case "exe" : 
						icoType = "folder-exe";
						break;
					default :
						icoType = "folder-file";
					
				}
            	icon = "<a href='javascript:;'><i class='inline-block folder-icon "+icoType+"'></i></a>";
            	f_name = "<span title='"+f.key+"'>"+f.key+"</span>"
            }else{
            	icon = "<a href='javascript:$startPorts = 1;$endPorts = 4;$addType = null;getVersionTree(\""+$dsId+"\",\""+path+"\",\""+$version+"\");'><i class='inline-block folder-icon folder-folder'></i></a>";
            	f_name = "<span title='"+f.key+"' style='cursor:pointer;' onClick='javascript:$startPorts = 1;$endPorts = 4;$addType = null;getVersionTree(\""+$dsId+"\",\""+path+"\",\""+$version+"\");'>"+f.key+"</span>"
            }
        	str+="<tr>";
        }
        str+="	<td width='93'>"+icon+"</td>"
        +"	<td width='157' class='g-al'>"+f_name+"</td>"
		/*+"	<td width='157' class='g-al'><input class='inp-name' type='text' value='"+f.name+"' readonly='readonly' style='width:153px'></td>"*/
		+"	<td width='93'>"+status+"</td>"
		+"	<td width='92'>"+f.type+"</td>"
		+"	<td width='111'>"+fileSize+"</td>"
		//+"	<td width='15%' class='g-al'><span class='tipspan'></span></td>";
		if(f.status=="失败"){
			str += "<td width='204' nid='"+f.nid+"' class='bartd' id='bartd"+i+"'>&nbsp;</td>";
		}else if(f.type == "文件夹"){
         	str += "<td width='204' nid='"+f.nid+"' class='bartd' id='bartd"+i+"'><button class='folder-table-btn c02' onclick='directors(\""+$dsId+"\",\""+path+"\",\""+$version+"\",\""+f.name+"\",\"bartd"+i+"\",\""+f.nid+"\")'>数据恢复</button></td>";
         }else{
         	str += "<td width='204' nid='"+f.nid+"' class='bartd' id='bartd"+i+"'><button class='folder-table-btn c02' onclick='files(\""+$dsId+"\",\""+path+"\",\""+$version+"\",\""+f.name+"\",\"bartd"+i+"\",\""+f.nid+"\",\""+f.key+"\")'>数据恢复</button></td>";
         }
		str += "</tr>";

    }
    $("#tbody").html(str);
    if($addType == "append"){
		var H = $(".folder-scroll").scrollTop() - 705;
		$(".folder-scroll").scrollTop(H);
	}else if($addType == "prepend"){
		var H = 705;
		$(".folder-scroll").scrollTop(H);
	}else{
		/*$onceUp = false;
		$onceDown = true;*/
		$(".folder-scroll").scrollTop("0");
	}
    /*if($startPorts == 1){
    	$("#tbody").html(str);
    }else{
    	$("#tbody").append(str);
    }*/
    getUploadProcessBarAll();
    getDownloadProcessBarAll();
    getImportDsBeanList();
    countByType(1);
    countByType(0);
};
var $dsId,$version,$path="/",$parent="",$root="",$startPorts = 1,$endPorts = 4,$pageSize = 15,$allPage = 1,$addType = ""/*,$onceDown = true,$onceUp = false;*/;
function getVersionTree(dsId,path,version,root,currentVersionMajor){
	$("#confirmBtn").css("color","#fff");
	if(currentVersionMajor == 0){
		plugin.msgtip({type: "e", msg: "该数据还没有备份过！"});
		return;
	}
	if(root){
		$root = root;
	}else if(path==""){
		$root = "\\";
	}
	if(path!=""){
		var idx = path.lastIndexOf("\\");
		if(idx!=-1){
			$parent = path.substring(0,idx);
			var idx2 = $parent.lastIndexOf("\\");
			if(idx2==-1){
				$parent = "\\";
			}
		}
	}
	if(path=="\\" || path=="\\/"){
		$('#currentPath').html($root==""?"\\":$root);
		path = "/";
	}else{
		if(path == "/"){
			$('#currentPath').html($root+"\\");
		}else{
			$('#currentPath').html($root+path);
			if($root+path == "\\"){
				$root = "";
			}
		}
	}
	if($startPorts == 1){
		$(".folder-scroll").scrollTop("0");
	}
	$dsId = dsId;
	$version = version;
	$path = path;
	service.getFileList({
		startPorts:$startPorts,
		endPorts:$endPorts,
		pageSize:$pageSize,
		dsId:dsId,
		version:version,
		path:encodeURIComponent(path)
	}, getVersionTreeCB);
}
function parentNode(){
	var path = $parent;
	$startPorts = 1;
	$endPorts = 4;
	$addType = "";
	if(path==""){
//		service.getDataSourcesByPage({
//			offset:0,
//			pagesize:10000,
//			dsType:"2",
//			status:"",
//			name:""
//		}, dsCB);
		getVersionTree($dsId,"",$version);
	}else if(path=="\\"){
		$parent = "";
		getVersionTree($dsId,"",$version);
	}else{
		getVersionTree($dsId,path,$version);
	}
}

function directors(dsId,path,version,name,bartd_id,nid){
	$("#h_dsId").val(dsId);
	$("#h_path").val(path);
	$("#h_bartd_id").val(bartd_id);
	$("#h_version").val(version);
	if(nid){
		$("#h_nid").val(nid);
	}
	service.getBackuplogs(getBackupWrapper(dsId), backupLogCB);
	
}
function files(dsId,path,version,name,bartd_id,nid,key){
	$("#h_dsId").val(dsId);
	$("#h_bartd_id").val(bartd_id);
	$("#h_path").val(path+"\\"+name);
	if(nid){
		$("#h_nid").val(nid);
	}
	var service1 = new EbeimService();
	service1.getFileChangeLog({
		dsId:dsId,
		path:encodeURIComponent(path),
		version:version,
		name:encodeURIComponent(key)
	}, fileChangeLogBC);
}

var fileChangeLogBC = function (data) {
	var json = data;
	var list = json.list;
	var size = list.length;
	var content = "";
	for (var i = 0; i < (list.length>5?5:list.length); i++) {
		var obj = list[i];
		content = content
		+"<li>"
		+"<span style='float:left;'><button class='btn j-recoveryBtn' data-version = '"+obj.version+"' data-dsId = '"+obj.datasourceId+"'>恢复至</button></span>"
		/*+"<span style='float:left;'><button onclick='recoveryClick(\""+obj.version+"\",\""+obj.datasourceId+"\")' class='btn'>恢复至</button></span>"*/
		+"<span style='float:right;'>"+getTimeStr(obj.logTime)+"</span>"
		+"</li>";
	}
	if(size==0){
		content = content
		+"<li style='text-align:center'>暂无可恢复的版本!</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
	
};

function getBackupWrapper(dsId) {
	var version = $("#h_version").val();
	if(version!=""){
		version = version.substring(0,version.indexOf("."));
	}
	var backupLog = {
		dsId : dsId,
		versionMajor:version,
		status:0
	}
	var pages = {
		startPos : 0,
		pageSize : 5
	}
	var bean = {
		path:$("#h_path").val()
	}
	var json = {};
	json["backupLog"] = backupLog;
	json["pages"] = pages;
	json["bean"] = bean;

	return json;
}

function recoveryClick(version,dsId,isRoot){
	$("#h_whichGetModel").val("recovery");
	$("#h_version").val(version);
	$("#h_dsId").val(dsId);
	if(isRoot==true){
		$("#h_path").val("/");
	}
	selectRecoveryPath("","recovery");
}

var backupLogCB = function(data){
	var list = data.list.objList;
	var size = list.length;
	var content = "";
	for (var i = 0; i < size; i++) {
		obj = list[i];
		content = content
		+"<li>" 
		+"<span style='float:left;'><button class='btn j-recoveryBtn' data-version = '"+obj.versionMajor+".0'  data-dsId = '"+obj.dsId+"' data-isRoot='"+data.isRoot+"'>恢复至</button></span>"
		/*+"<span style='float:left;'><button onclick='recoveryClick(\""+obj.versionMajor+".0\",\""+obj.dsId+"\","+data.isRoot+")' class='btn'>恢复至</button></span>"*/
		+"<span style='float:right;'>"+getTimeStr(obj.beginTime)+"</span>"
		+"</li>";
	}
	if(size==0){
		content = content
		+"<li style='text-align:center'>暂无可恢复的版本!</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
};
function selectRecoveryPath(path,recovery){
	$(".window").css("display","block");
	$(".shadowDiv").css("display","block");
	while(path.charAt(path.length - 1) == "\\" && path.charAt(path.length - 2) != ":"){
		path = path.substring(0,path.length-1)
	}
	$("#ab-dir").val(path);
	service.getSystemDirs(
		{
			path:path,
			action:recovery
		},
		function(data){
			selectPathCB(data,recovery);
		}
	);
	/*var abDir = $("#ab-dir").val();
	if(abDir!=""){
		$("#ab-dir").val(abDir+"\\"+path);
		service.getSystemDirs({
			path:abDir+"\\"+path,
			action:recovery
		}, function(data){
			selectPathCB(data,recovery);
		});
	}else{
		$("#ab-dir").val(path);
		service.getSystemDirs({
			path:path,
			action:recovery
		}, function(data){
			selectPathCB(data,recovery);
		});
	}*/
}
var selectPathCB = function(data,recovery){
	if(data.code == "500"){
		plugin.msgtip({type: "e", msg: "系统找不到该路径！"});
		return false
	}
	var json = data;
	var content = "";
	if(onceKey == true){
		onceKey = false;
		getPathTree(data,pathNodes);
		$.fn.zTree.init($("#pathTree"), pathSet, pathNodes);
	}
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		
		var showName = name;
		if(showName.indexOf("\Desktop")!=-1){
			showName = "桌面"
			name = name.split("\\").join("\\\\");
		}
		if(recovery){
			content = content +
			"<li class='j-recovery' title='"+name+"' data-path='"+json[i].absolutePath+"'><a href='javascript:;'><p>"+showName+"</p></a></li>";
		}else{
			content = content +
			"<li class='j-path' title='"+name+"' data-path='"+json[i].absolutePath+"'><a href='javascript:;'><p>"+showName+"</p></a></li>";
		}
	}
	$(".w-dir-list ul").html(content);
}
function selectSafeboxPath(path){
	$(".window").css("display","block");
	$(".shadowDiv").css("display","block");
	var abDir = $("#ab-dir").val();
	if(abDir!=""){
		$("#ab-dir").val(abDir+"\\"+path);
		service.getSystemDirs({
			path:abDir+"\\"+path
		}, selectPathCB);
	}else{
		$("#ab-dir").val(path);
		service.getSystemDirs({
			path:path
		}, selectPathCB);
	}
}
function selectParentPath(path){
	var abDir = $("#ab-dir").val();
	var idx = abDir.lastIndexOf("\\");
	if(abDir.charAt(abDir.length - 2) != ":" && idx!=-1){
		abDir = abDir.substring(0,idx);
		if(abDir.charAt(abDir.length - 1) == ":"){
			abDir = abDir+"\\";
		}
		$("#ab-dir").val(abDir);
    	service.getSystemDirs({
    		path:abDir
    	}, selectPathCB);
	}else{
		$("#ab-dir").val("");
		service.getSystemDirs({
			path:""
		}, selectPathCB);
	}
}

function confirmDir(){
	var h_whichGetModel =  $("#h_whichGetModel").val();
	if(h_whichGetModel == "importDs"){
		importDs();
	}else if(h_whichGetModel == "recovery"){
		var version = $("#h_version").val();
		recovery(version);
	}else{
		plugin.msgtip({type:"e",msg:"参数缺失!"});
	}
}
function cancelDir(){
	clearDateAndWindow();
}

function recovery(version,dynamicCode){
	var dsId = $("#h_dsId").val();
	var path ="/"+$("#h_path").val();
	var abDir = $("#h_abDir").val();
	/*var abDir = $("#ab-dir").val();*/
	var nid = $("#h_nid").val();
	if(abDir == ""){
		plugin.msgtip({type:"e",msg:"请选择下载目录"});
		return;
	}
	$("#confirmBtn").css("color","gray");
	service.recoveryFile({
		dsId:dsId,
		rootTreeDsId:$dsId,
		path:encodeURIComponent(path),
		version:version,
		dynamicCode:dynamicCode,
		abDir:encodeURIComponent(abDir),
		nid:nid
	}, recoveryCB);
}

var recoveryCB = function(data){
	$("#confirmBtn").css("color","#fff");
	var json = data;
	var dsId = json.dsId;
	if(json.code=="200" || json.code==200){
		
		clearDateAndWindow();
		
//		$("#status"+dsId).html("备份中");
//		
//		var td_id = $("#h_bartd_id").val();
//    	$("#"+td_id).parent().find("td").find(".tipspan").html("等待链接...");
//   		var content = ""
//   		+"<div style='width:100px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
//   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
//   		+"<div class='r-info' style='position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
//   		+"</div>";
//   		
//   		var td_id = $("#h_bartd_id").val();
//   		$("#"+td_id).html(content);
   		
	 }else{
		 dsSecurityRankCheck(json,json.message);
	 }
}

function clearDateAndWindow(){
	$("#dynamicCode").val("");
	$("#ab-dir").val("");
	hideDialog("versionWindow");
	closeCodeWindow();
	onceKey = true;
	$(".window").css("display","none");
	$(".shadowDiv").css("display","none");
}

function setDynamicCode(){
	var dynamicCode = $("#dynamicCode").val().replace(/(^\s+)|(\s+$)/g,"");
	if(dynamicCode == ""){
		 plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
		return;
	}
	var h_whichGetModel = $("#h_whichGetModel").val();
	if(h_whichGetModel=="handBackup"){
		var dsSecurityRank = $("#h_dsSecurityRank").val();
		handBackup($dsId, dsSecurityRank, dynamicCode);
	}else{
		var version = $("#h_version").val();
		recovery(version,dynamicCode);
	}
	
}

function getDownloadProcessBar() {

	var ids = "";
	$(".bartd").each(function() {
		ids += $(this).attr("nid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		service.getDownloadProcessBar({
			nids:ids
		}, processbarCB);
		service.deleteDownloadProcessBar({
			nids:ids
		});
	}
}


var processbarCB = function(data){
	var json = data;
	var list = json.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		$(".bartd").each(function(){
			var nid = $(this).attr("nid");
			if (nid == bean.nid) {
				var count = bean.count;
				var total = bean.total;
				var fileSum = bean.fileSum;
				var okSum = bean.okSum;
				var errorSum = bean.errorSum;
				var percent = (count/total)*100;
				
				var content = ""
			   		+"<div style='width:100px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
			   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
			   		+"<div class='r-info' style='position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
			   		+"</div>";
				$(this).html(content);
				
				if(count >= total || (okSum+errorSum)>=fileSum && errorSum!=fileSum){
					$(this).parent().find("td").find(".tipspan").html("");
					$(this).html("下载完成!");
					if(bean.nid.indexOf('DS-')!=0){ 
						setTimeout(function(){
							$("#j-reset").click();
						}, 3000);
					}
					if(total==0){
						service.deleteDownloadProcessBarByNid({nid:nid}, function(data){;})
					}
				}else if(count == -1 || errorSum==fileSum){
					$(this).find(".r-info").html("<font color='red'>下载失败！</font>");
					service.deleteDownloadProcessBarByNid({
						nid:nid
					}, function(data){;});
				}else{
	    			$(this).parent().find("td").find(".tipspan").html("正在下载...");
	    			$(this).find("#processbar").css("width",percent+"%");
	    			$(this).find("#percentage").html((Math.floor(percent*100)/100)+"%");
				}
			}
		});
	}
}
var delProcessbarCB = function(data) {
	var json = data;
	if(json.code=="200"){
		$startPorts = 1;
		$endPorts = 4;
		$addType = "";
		getVersionTree($dsId, $path, $version, $root, 1);
	}
}


$(function(){
	initTree();
})

function initTree(reload){
	var setting;
	var zNodes =[];
	setting = {
		async: {
            enable: true,
            url: "/rest/datasource/menu",
            autoParam: ["id","type","version","path","dsId","requestType"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	if(responseData.code == "200"){
            		var nodes = [];
                	getTree(responseData.list,nodes,reload);
                	return nodes;
            	}else{
            		plugin.msgtip({type: "e",msg: responseData.message});
            	}
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick,
            onExpand:function(event, treeId, treeNode){
            	var treeObj = $.fn.zTree.getZTreeObj(treeId);
            	var unableNodes = treeObj.getNodesByParam("unable", true);
    			if (unableNodes.length>0) {
    				for(var i in unableNodes){
    					$("#"+unableNodes[i].tId+"_ico").css({"cursor":"default"});
    				}		
    			}
            }
        }
    };
	
	service.getMenuTree({type:"0",requestType:"0"},function(json){
		if(json.code == "200"){
			getTree(json.list,zNodes,reload);
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var unableNodes = treeObj.getNodesByParam("unable", true);
			if (unableNodes.length>0) {
				for(var i in unableNodes){
					$("#"+unableNodes[i].tId+"_a").css({"cursor":"default","text-decoration":"none"});
					$("#"+unableNodes[i].tId+"_ico").css({"cursor":"default"});
				}		
			}
			var terminalNodes = treeObj.getNodesByParam("id", json.list[0].id);
			if (terminalNodes.length>0) {
				treeObj.expandNode(terminalNodes[0], true ,false,true,true);		
			}
		}else{
			plugin.msgtip({type: "e",msg: json.message});
		}
		
	});
}
    
function onClick(e,treeId, treeNode) {
	if(!treeNode.dsId){
		$("#"+treeNode.tId+"_a").removeClass("curSelectedNode");
		return false;
	}
	if(treeNode.root!=undefined && treeNode.root !=""){
		$root = treeNode.root;
	}
	if(treeNode.dsId!=""){
		$startPorts = 1;
		$endPorts = 4;
		$addType = "";
		getVersionTree(treeNode.dsId,treeNode.path,treeNode.version);
	}
}
function getFont(treeId, node) {
    return node.font ? node.font : {};
}
var args = {}; 
function getTree(json,nodes,reload){
	for(var i = 0;i<json.length; i++){
		var data = {};
		data.id = json[i].id;
		data.name = json[i].name;
		data.pId = json[i].pid;
		data.type = (parseInt(json[i].type) + 1)+"";
		data.version = json[i].version;
		data.path = json[i].path;
		data.dsId = json[i].dsId;
		data.requestType = json[i].requestType;
		data.root = json[i].root;
		data.isParent = true;
		if(json[i].type == "0"){
			data.iconSkin = "sty01"
			$dsId = data.dsId;
			$version = data.version;
			$path = $("#currentPath").html();
		}else if(json[i].type == "1"){
			data.iconSkin = "sty02"
		}else{
			data.iconSkin = "sty03"
		}
		nodes[i] = data;
	}
	var root;
	if(data){
		root = data.root;
	}
	if(!reload){
		$startPorts = 1;
		$endPorts = 4;
		$addType = "";
		getVersionTree($dsId,$path,$version,root,1);
	}
}

function createFolder(){
	
	var folderName = $("#folderName").val().replace(/(^\s+)|(\s+$)/g,"");
	if(folderName==""){
		plugin.msgtip({type: "e", msg: "文件夹名称不能为空!"});
		return;
	}else if(plugin.checkFn.isFileName(folderName)){
		plugin.msgtip({type: "e", msg: "文件夹名称不能包含下列任何字符: \\/:*?\"<>|"});
		return;
	}
	$path = $("#currentPath").html();
	$path = $path.split("\\\\").join("\\");
	service.createVersionTreeFolder({
		dsId:$dsId,
		version:$version,
		path:$path,
		folderName:folderName
	}, function(data){
		if(data.code == "500"){
			plugin.msgtip({type: "e",msg: "已有目录正在生成中，请稍候再试"});
		}else{
			hideDialog("createFolderWindow",false,function(){
				initTree(true);
				$startPorts = 1;
				$endPorts = 4;
				$addType = "";
				getVersionTree($dsId, $path, $version, $root, 1);
			});
		}
		
	},function(data){
		plugin.msgtip({type: "e",msg: "操作失败，请重试"});
	});
}

function nodeReload(){
	$startPorts = 1;
	$endPorts = 4;
	$addType = "";
	$path = $("#currentPath").html();
	$path = $path.split("\\\\").join("\\");
	getVersionTree($dsId, $path, $version, $root, 1);
}

function getFont(treeId, node) {
    return node.font ? node.font : {};
}
function getPathTree(json,nodes){
	var j = 0;
	for(var i = 0;i<json.length; i++){
		var data = {};
		if(json[i].isParent){
			if(json[i].name.indexOf("\Desktop")!=-1){
				data.name = "桌面"
			}else{
				data.name = json[i].name;
			}
			data.path = json[i].absolutePath;
			data.isParent = json[i].isParent;
			data.iconSkin = "path";
			
			nodes[j] = data;
			j++;
		}	
	}
}

function pathClick(e,treeId, treeNode) {
	selectRecoveryPath(treeNode.path);
}

function getImportDsBeanList(){
	service2.getImportDsBeanList({
		
	}, function(data){
		var beans = data.list;
		var importingWindowTB = "";
		//合并到上传记录的tag数量
		$uploadTag = beans.length;
		for(var i = 0; i<beans.length; i++){
			var bean = beans[i];
			var info = "";
			var btn = "<a class='delImportingBtn' id='"+bean.id+"' href='javascript:deleteImporting(\""+bean.id+"\");'>删除</a>";
			if(bean.status==1){
				info = "<font color='gray'>正在生成目录结构...</font><img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>";
				btn = "";
			}else if(bean.status==2){
				info = "<font color='red'>"+bean.remark+"</font>";
				$(".j-deleteUp").css("display","inline-block");
				$(".j-undeleteUp").css("display","none");
			}else if(bean.status==3){
				info = "<font color='green'>成功生成目录结构，即将开始上传数据...</font>";
				info = "";
				service2.updateImportStaus({
					id:bean.id,
					status:6
				},function(data){
					if(data.code=="200"){
						$version = data.version;
						initTree(true);
						$path = $("#currentPath").html();
						$path = $path.split("\\\\").join("\\");
						getVersionTree($dsId, $path, $version, $root, 1);
					}
				});
				continue;
			}else if(bean.status==4){
				info = "<font color='green'>成功生成目录结构，即将开始上传数据...</font>";
				info = "";
				service2.updateImportStaus({
					id:bean.id,
					status:4
				},function(data){
					if(data.code=="200"){
						service2.deleteImporting({
							ids:data.id
						},function(data){
							
						});
						$version = data.version;
						initTree(true);
						$path = $("#currentPath").html();
						$path = $path.split("\\\\").join("\\");
						getVersionTree($dsId, $path, $version, $root, 1);
					}
				});
				continue;
			}else if(bean.status==5){
				info = "";
				continue;
			}else if(bean.status==6){
				btn = "";
				info = "<font color='green'>成功生成目录结构，即将开始上传数据...</font><img src='/web/images/loading.gif' style='margin-bottom: -3px; margin-left: 3px;'>";
			}
			importingWindowTB = importingWindowTB
			+"<tr>"
			+"	<td><nobr style='max-width:300px;display:inline-block;overflow:hidden;text-overflow:ellipsis;'>"+bean.name+"</nobr></td>"
			+"	<td width='350px' style='text-align:center;font-size:12px;'>"
			+ info
			+"</td>"
			+"	<td width='60px;' style='text-align:center;'>"+btn+"</td>"
			+"</tr>";
		}
		$("#importingWindowTB").html(importingWindowTB);
	});
}

function deleteImporting(id){
	if(!id){
		id = "";
		$(".delImportingBtn").each(function(){
			id += $(this).attr("id")+",";
		});
		if(id.length>0){
			id = id.substring(0,id.length-1);
		}
	}
	if(!id || id.length==0){
//		plugin.msgtip({type:"e",msg:"还没有可以删除的记录!"});
		return;
	}
	service2.deleteImporting({
		ids:id
	}, function(data){
		//TODO
	});
}

function setUable(id){
	$(".j-deleteUp").css("display","none");
	$(".j-undeleteUp").css("display","inline-block");
}
